<style lang="scss">
  @import "../../utils/base.scss";
	.demo-drawer-footer{
		width: 100%;
		// position: absolute;
		bottom: 0;
		left: 0;
		border-top: 1px solid #e8e8e8;
		padding: 10px 16px;
		text-align: right;
		background: #fff;
	}
	.myText{
		max-width: 200px;
		max-height: 150px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
  .ivu-table-stripe .ivu-table-body tr, .ivu-table-stripe .ivu-table-fixed-body tr {
      background-color: #ffffff;
  }
  td.ivu-table-expanded-cell {
    padding: 0px;
	}
  .myLabel{
    display: inline-block;
    padding-bottom: 5px;
  }
</style>
<template>
  <div>
    <pheader :width="'15%'">
      <template slot="left">租户管理/租户配置</template>
      <div style="text-align: right;margin-right: 32px;" slot="right">
        <Button type="primary" size="small" @click="add()" v-if="this.$hasPerm('tenantAdd')">新增</Button>
      </div>
    </pheader>
    <tabContent>
      <template slot="content">
        <div>
          <div class="myLabel">
            <label>租户名称</label>
            <Input v-model="searchInfo.tenant_name" placeholder="租户名称" style="width: 150px;" @on-enter="search(0)"/>
          </div>
          <div class="myLabel" style="padding-left: 5px">
            <label>运营人员</label>
            <Input v-model="searchInfo.business" placeholder="运营人员" style="width: 150px;" @on-enter="search(0)"/>
          </div>
          <div class="myLabel" style="padding-left: 5px">
            <label>用户名称</label>
            <Input v-model="searchInfo.user_name" placeholder="用户名称" style="width: 150px;" @on-enter="search(0)"/>
          </div>
          <div style="float:right;">
            <Button type="primary" @click="search(0)">查询</Button>
            <Button type="primary" @click="refresh()">重置</Button>
          </div>
        </div>

        <Table border :columns="columns" :data="data" :loading="tableLoading">
          <template slot-scope=" { row, index }" slot="tenant_name">
            <span>{{ row.tenant_name}}</span>
          </template>
          <template slot-scope=" { row, index }" slot="des">
            <div class="myText">
              <span>{{row.des}}</span>
            </div>
          </template>
          <template slot-scope=" { row, index }" slot="projects">
            <div class="myText">
              <span>{{showProjects(row.projects)}}</span>
            </div>
          </template>
          <template slot-scope=" { row, index }" slot="users">
            <div class="myText">
              <span>{{showUsers(row.users)}}</span>
            </div>
          </template>
          <template slot-scope=" { row, index }" slot="action">
            <div style="display: inline-block;">
              <a v-if="$hasPerm('tenantEdit')" href="javascript:void(0)" @click="edit(index,row)">
                <div class="text_link" style="width: 50px;">
                  编辑
                </div>
              </a>
              <a v-if="$hasPerm('tenantMove')" href="javascript:void(0)" @click="deleteTenant(row)">
                <div class="text_link" style="width: 50px;">
                  删除
                </div>
              </a>
            </div>
          </template>
        </Table>
        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
            <Page :current="page" :total="total" show-total show-elevator show-sizer @on-change="changePage"
              @on-page-size-change="changePageSize"></Page>
          </div>
        </div>
        <Modal @on-ok="add_ok()" @on-cancel="cancel('add_menu')" v-model="add_menu.show" :loading="loading" :title="!add_menu.isupdate?'新增租户':'编辑租户'"
          width="720">
          <Form ref="add_menu" :model="add_menu" :rules="ruleInline" label-position="left" :label-width="115">
            <Row >
              <Col span="23"style="width:97%" >
              <FormItem label="租户名称：" prop="tenant_name">
                <Input v-model="add_menu.tenant_name" @on-change="checkTenant" />
              </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="23" style="width:97%">
              <FormItem label="租户运营人员：" :required="true">
                <component ref="inputSearch"  :dataList="businessList"  :checkLable="add_menu.businessId" :is="'inputSearch'"
                   :multiple="false" :isSysUser="false" @on-change="getBusiness" style="width:200px"></component>
              </FormItem>
              </Col>
            </Row>
<!--             <Row>
              <Col span="23" style="width:97%">
              <FormItem label="关联YX租户：" :required="true">
                <Select v-model="add_menu.yxpaasTenantId" filterable style="width:200px" placeholder="请选择关联的YX租户">
                  <Option v-for="(item, index) in yxpaasList" :value="item.id" :key="index">{{item.name}}</Option>
                </Select>
              </FormItem>
              </Col>
            </Row> -->
            <Row >
              <Col span="23" style="width:97%">
              <FormItem label="租户描述：" prop="des">
                <Input v-model="add_menu.des" type="textarea" :rows="3" />
              </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="10" >
              <FormItem label="关联用户：">
                <Select v-model="add_menu.usersId" multiple filterable remote :remote-method="remoteMethod" :loading="loading2"
                  style="width:550px" placeholder="请搜索用户" @on-change="changeUsers">
                  <Option v-for="(option, index) in userList" :value="option.id" :key="index">{{option.user_name}}</Option>
                </Select>
              </FormItem>
              </Col>
            </Row>
          </Form>
        </Modal>

      </template>
    </tabContent>
  </div>
</template>

<script>
  import expandRow from './tenant_expand.vue'
  import mpage from "../../comp_chatter/mpage"
  import pheader from "../../comp_chatter/pheader"
  import mheader from "../../comp_chatter/mheader"
  import mcontainer from "../../comp_chatter/mcontainer"
  import Axios from 'axios'
  import ajax from "../../ajax_util"
  import inputSearch from '../../base/input_search'
  import tabContent from "../../comp_chatter/tab_content.vue"

  export default {
    components: {
      expandRow,
      mpage,
      mheader,
      mcontainer,
      pheader,
      inputSearch,
      tabContent
    },
    data() {
      const validateTenant_name = (rule, value, callback) => {
        this.tenant_repetition = -1;
        if (value === '') {
          callback(new Error('请输入租户名称.'));
        }
        // else if( (!this.add_menu.isupdate) || (this.add_menu.isupdate&&this.ifTenant) ){
        // 	if(this.tenant_repetition==1){
        // 		this.tenant_repetition=1;
        // 		callback(new Error('该租户已存在!'));
        // 	}
        // 	callback();
        // }
        else {
          callback();
        }
      };
      return {
        tableLoading: false,
        ruleInline: {
          tenant_name: [{
            required: true,
            validator: validateTenant_name,
            trigger: 'blur'
          }],
          des: [{
            required: true,
            message: '请输入租户描述.',
            trigger: 'blur'
          }]
        },
        add_menu: {
          show: false,
          tenant_name: "",
          des: "",
          businessId: 0,
          usersId: [],
          isupdate: false,
          updateId: -1,
        },
        businessList: [],
        loading: true,
        data: [],
        tenant_nameList: [],
        tenant_repetition: -1,

        page: 1,
        pageSize: 10,
        total: 0,
        searchInfo: {
          tenant_name:"",
          business:"",
          user_name:""
        },
        search_param:"",
        filterList: [],
        methodId: '0',

        permShow: false,
        menuList: [],
        permList: [],
        apiList: [],
        treeList: [],
        checkList: [11],
        addPerms: [11],

        newMenuList: [],
        userList: [],
        allNameList: [],
        loading2: false,

        temp_tenant: "",
        ifTenant: false,

        typeList: [{
            value: "business",
            label: "运营管理"
          },
          {
            value: "operation",
            label: "运维管理"
          },
          {
            value: "safe",
            label: "安全管理"
          },
          {
            value: "entry",
            label: "普通角色"
          }
        ],

        leftNotFindMsg: "列表为空",
        leftCheckAll: false, //左边全选按钮
        leftCheckList: [], //左边选择集合
        leftInfoList: [], //左边数据集合
        leftInput: "", //左边搜索值

        rightCheckAll: false, //右边全选按钮
        rightCheckList: [], //右边选择集合
        rightInfoList: [], //右边数据集合
        rightInput: "", //右边搜索值
        rightInfoListTemp: [], //右边选择框原始数据

        yxpaasList:[],
      }
    },
    computed: {
      columns() {
        let columns = [];
        columns.push({
          type: 'expand',
          width: 50,
          render: (h, params) => {
            return h(expandRow, {
              style: {
                'background-color': '#ffffff',
              },
              props: {
                row: params.row,
                projects: this.showProjects(params.row.projects)
              }
            })
          }
        });
        columns.push({
          title: '租户名称',
          key: 'tenant_name',
          slot: 'tenant_name',
          minWidth: 100,
          maxWidth: 240
        });
        columns.push({
          title: '租户运营人员',
          key: 'business',
          width: 120
        });
        columns.push({
          title: '租户描述',
          slot: 'des',
          minWidth: 100
        });
        columns.push({
          title: '租户下的项目',
          slot: 'projects',
          minWidth: 100
        });
        columns.push({
          title: '租户下的用户',
          slot: 'users',
          width: 250
        });
        if (this.$hasPerm('tenantEdit') || this.$hasPerm('tenantMove')) {
          columns.push({
            title: '操作',
            key: 'action',
            width: 138,
            align: 'center',
            slot: "action",
          });
        }
        return columns;
      }
    },
    mounted() {
      this.search(0);
    },
    methods: {
      showProjects(projects) {
        //console.log("----projects----",projects);
        var str = "";
        for (var i = 0; i < projects.length; i++) {
          str = str + projects[i].project + "、"
        }

        str = str.slice(0, str.length - 1);
        return str;
      },
      showUsers(users) {
        var str = "";
        for (var i = 0; i < users.length; i++) {
          str = str + users[i].user_name + "、"
        }

        str = str.slice(0, str.length - 1);
        return str;
      },
      search(number) {
        this.tableLoading = true;

        if (number == 0) {
          this.page = 1;
        }

        var pageModel = {};
        pageModel.page = this.page;
        pageModel.pageSize = this.pageSize;
        pageModel.searchInfo = this.searchInfo
        var that = this;
        var url = this.CONFIG.url_know + '/searchTenants';
        ajax.post({
          url: url,
          that: that,
          data: pageModel,
          success: function(data) {
            console.log("----data-------",data);
            that.total = data.total;
            that.data = data.tenantList;
            that.tableLoading = false;
          }
        })
      },
      refresh(){
        this.searchInfo.tenant_name = "";
        this.searchInfo.business = "";
        this.searchInfo.user_name = "";
        this.search(0);
      },
      changePage(page) {
        this.page = page;
        this.search(1);
      },
      changePageSize(pageSize) {
        this.pageSize = pageSize;
        this.search(0);
      },
      messageWarningFn(text) {
        this.$Message.warning(text)
        setTimeout(() => {
          this.loading = false
          this.$nextTick(() => {
            this.loading = true
          });
        }, 0.1);
      },
      cancel(name) {
        this.$refs[name].resetFields();
        this.add_menu.businessId = 0;
        this.ifTenant = false;
        this.tenant_repetition = -1;
      },
      checkTenant() {
        if (this.add_menu.tenant_name == this.temp_tenant) {
          this.ifTenant = false;
        } else {
          this.ifTenant = true;
        }
      },
      add_ok() {
        //console.log("----this.add_menu-----",this.add_menu);
        var that = this;
        if (this.add_menu.tenant_name === '') {
          this.messageWarningFn('租户名称不能为空!');
          return
        }
        // else if( this.tenant_repetition === 1 ){
        // 	this.messageWarningFn('该租户已存在!');
        // 	return
        // }
        else if (this.add_menu.businessId == 0 || this.add_menu.businessId == undefined || this.add_menu.businessId ==
          null) {
          this.messageWarningFn('租户运营人员不能为空!');
          return
        } else if (this.add_menu.des === '') {
          this.messageWarningFn('租户描述不能为空!');
          return
        } else {
          var url = this.CONFIG.url_know + '/tenant'
          let tenant = {
            tenant_name: this.add_menu.tenant_name,
            des: this.add_menu.des,
            businessId: this.add_menu.businessId,
            userIdList: this.add_menu.usersId,
            ifTenant: this.ifTenant,
          };
          if (this.add_menu.isupdate) { //说明是修改，不是新增
            console.log("-------------", tenant);
            tenant["id"] = this.add_menu.updateId;
            ajax.put({
              url: url,
              that: that,
              data: tenant,
              success: function(data) {
                console.log("---------", data);
                if (data == 0 && that.ifTenant) {
                  //that.tenant_repetition = 1;
                  that.messageWarningFn('该租户名称已存在!');
                } else {
                  that.$Notice.success({
                    title: '成功修改租户'
                  });
                  that.add_menu.show = false;
                  that.ifTenant = false;
                  that.search(1);
                }

              }
            })
          } else { //说明是新增
            ajax.post({
              url: url,
              that: that,
              data: tenant,
              success: function(data) {
                if (data == 0) {
                  //that.tenant_repetition = 1;
                  that.messageWarningFn('该租户名称已存在!');
                } else {
                  //that.get_all_tenant();
                  that.$Notice.success({
                    title: '成功新建租户'
                  });
                  that.add_menu.show = false;
                  that.ifTenant = false;
                  that.search(0);
                }
              }
            })
          }
        }
      },
      add() {
        if(this.allNameList.length<1){
          this.getUsersName();
        }

        this.businessList = [];
        this.add_menu.isupdate = false;
        this.add_menu.show = true;
        this.add_menu.tenant_name = "";
        this.add_menu.des = "";
        this.add_menu.businessId = 0;
        this.add_menu.usersId = [];
        this.userList = [];
      },
      edit(index, row) {
        if(this.allNameList.length<1){
          this.getUsersName();
        }

        this.add_menu.isupdate = true;
        this.add_menu.updateId = row.id;

        this.add_menu.tenant_name = row.tenant_name;
        this.add_menu.des = row.des;
        this.add_menu.businessId = row.businessId;

        this.temp_tenant = row.tenant_name;

        let tempList = [];
        for (var i = 0; i < row.users.length; i++) {
          tempList.push(row.users[i].id);
        }
        this.add_menu.usersId = tempList;
        this.userList = row.users;

        this.businessList = [];
        var j = {};
        j.id = row.businessId;
        j.user_name = row.business;
        this.businessList.push(j);

        this.getBusiness(this.businessList);
        this.add_menu.show = true;
        console.log("--row--", row);
      },
      getUsersName() {
        var that = this;
        var url = this.CONFIG.url_know + '/get-users';
        ajax.get({
          url: url,
          that: that,
          success: function(data) {
            //console.log("----data-------",data);
            that.allNameList = data;
            // that.search(that.search_param, 0);
            //that.$forceUpdate();
          }
        })
      },
      getBusiness(data) {
        //console.log("--7777777------",data,this.businessList);
        if (data != undefined && data != null && data.length != 0 && data[0] != undefined && data[0] != null) {
          console.log("!!!!!!!", data);
          this.add_menu.businessId = data[0].id;
        }
        console.log("--businessId------", this.add_menu.businessId, this.businessList);
      },
      deleteTenant(row) {
        if (row.projects != null && row.projects.length > 0) {
          this.$Modal.warning({
            title: '该租户下有项目，不能删除!',
            width: '365'
          });
        } else {
          this.$Modal.confirm({
            title: '确定删除该租户？',
            width: '360',
            onOk: () => {
              this.del(row.id)
            }
          });
        }
      },
      del(id) {
        var that = this;
        var url = this.CONFIG.url_know + '/tenant/' + id;
        ajax.del({
          url: url,
          that: that,
          success: function() {
            if (that.data.length === 1 && that.page > 1) {
              that.page = that.page - 1;
            }
            that.search(1);
            that.$Notice.success({
              title: '成功删除租户'
            });
          }
        });
      },
      remoteMethod(query) {
        //console.log("===query=====",query);
        //this.userList = [];
        if (query !== '') {
          this.loading2 = true;
          setTimeout(() => {
            this.loading2 = false;
            const allNameList = this.allNameList.map(item => {
              return {
                id: item.id,
                user_name: item.user_name
              };
            });
            console.log("===222=====", query);
            this.userList = allNameList.filter(item => item.user_name.indexOf(query) > -1);
          }, 200);
        } else {
          this.userList = [];
        }
      },
      changeUsers(data) {
        //console.log("========",this.add_menu.usersId);
      }
    }
  }
</script>
